package com.lizardmind.haofudoctor.ui.other

import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.view.KeyEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import com.blankj.utilcode.util.SizeUtils
import com.just.library.AgentWeb
import com.linxiao.framework.activity.BaseActivity
import com.linxiao.framework.util.color
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.other.js.ShareJS
import com.lizardmind.haofudoctor.other.jsonOf
import com.lizardmind.haofudoctor.other.rongYun.MessageTags
import com.lizardmind.haofudoctor.other.rongYun.PatientsEducationMessage
import com.lizardmind.haofudoctor.other.rongYun.USER_PREFIX
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import kotlinx.android.synthetic.main.include_title_text.*
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * 患者教育的网页
 * Created by Extends on 2017/12/11 14:32
 */
class PatientsEduWebActivity : BaseActivity() {
    private val uid by lazy { intent.getStringExtra("uid")?:"" }
    private val url by lazy { intent.getStringExtra("url")?:"file:///android_asset/html/error.html" }
    private lateinit var web:WebView
    private lateinit var mAgentWeb:AgentWeb
    private val share = ShareJS()
    override fun onCreatRootView(): View? {
        return linearLayout {
            orientation = LinearLayout.VERTICAL
            include<ConstraintLayout>(R.layout.include_title_text)
            mAgentWeb = AgentWeb.with(this@PatientsEduWebActivity)
                    .setAgentWebParent(this,LinearLayout.LayoutParams(-1,-1,1f))
                    .useDefaultIndicator()
                    .defaultProgressBarColor()
                    .setWebViewClient(object :WebViewClient(){
                        override fun onPageFinished(view: WebView, url: String) {
                            view.loadUrl("javascript:window.shareJS.setShareJS(getData)")
                            super.onPageFinished(view, url)
                        }
                    })
                    .setReceivedTitleCallback { view, title -> titleText.text = title }
                    .createAgentWeb()
                    .ready()
                    .go(url)
                    .apply {
                        jsInterfaceHolder.addJavaObject("shareJS",share)
                        web = webCreator.get()
                    }
            if(uid.isNotEmpty()){
                button("立即发送"){
                    background = resources.getDrawable(R.drawable.btn_bg_fill)
                    textColor = color(R.color.white)
                    onClick {
                        if(share.title==null|| share.synopsis==null||share.imgUrl==null){
                            toast("获取信息失败，请刷新后再试")
                            return@onClick
                        }
                        RongIM.getInstance().sendMessage(
                                Message.obtain(USER_PREFIX + uid, Conversation.ConversationType.PRIVATE, PatientsEducationMessage(
                                        jsonOf("title" to share.title,"content" to share.synopsis,"img" to share.imgUrl,"url" to url)
                                )),
                                MessageTags.PATIENTS_EDUCATION,
                                null,
                                object : io.rong.imlib.IRongCallback.ISendMessageCallback {
                                    override fun onAttached(p0: Message) {}
                                    override fun onSuccess(p0: Message) {
                                        toast("发送成功")
                                    }
                                    override fun onError(p0: Message?, p1: RongIMClient.ErrorCode) {}
                                }
                        )
                    }
                }.lparams(-1,SizeUtils.dp2px(50f))
            }
        }
    }

    override fun onInitView(savedInstanceState: Bundle?) {
        imgLeft.setImageResource(R.mipmap.back)
        imgLeft.onClick { finish() }
        titleText.text = ""


    }


    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && web.canGoBack()) {
            web.goBack() // goBack()表示返回WebView的上一页面
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}